package com.sto.stoapp.db.manager;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.StoBaseConstant;
import com.sto.stoapp.db.constant.StoSiteCodeConstant;
import com.sto.stoapp.entity.BaseEntity;
import com.sto.stoapp.entity.SiteCodeEntity;
import com.sto.stoapp.http.response.download.info.OrgInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 网点全表管理类
 * 
 * @author mgf
 * 
 */
public class SiteFullManager extends StoDataBase implements
		DownLoadDao<OrgInfo> {

	private static SiteFullManager manager;

	private static final String SQL_QUERY_ALL = "select * from "
			+ SITE_CODE_FULL_TABLE + " where 1=1";

	private static final String SQL_QUERY_COUNT = "select count(*) from "
			+ SITE_CODE_FULL_TABLE + " where 1=1";

	// 搜索网点某一条数据
	public static final String SQL_NETSITE_ONLY = "select * from "
			+ SITE_CODE_FULL_TABLE + " where " + SITE_CODE_NUMBER + " = ? ";

	private SiteFullManager(Context context) {
		super(context);
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static SiteFullManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (manager == null) {
				manager = new SiteFullManager(context);
			}
			return manager;
		}
	}

	/**
	 * 插入单条数据
	 * 
	 * @param entity
	 * @return
	 */
	public boolean insert(OrgInfo info) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				ContentValues values = new ContentValues();
				values.put(SITE_CODE_NUMBER, info.getKey());
				values.put(SITE_CODE_NAME, info.getValue());
				values.put(StoSiteCodeConstant.ID, info.id);
				values.put(StoSiteCodeConstant.VERSION, info.getVersion());
				values.put(StoSiteCodeConstant.BACKUP1, info.getBackup1());
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(SITE_CODE_FULL_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条网点全表", "成功");
				} else {
					Log.d("插入一条网点全表", "失败");
				}
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}


	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(SITE_CODE_FULL_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}
	/**
	 * 批量更新数据
	 * 
	 * @param datas
	 */
	public void insertList(List<BaseEntity> datas) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int length = datas.size();
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (int i = 0; i < length; i++) {
					long res = -1;
					SiteCodeEntity siteCodeEntity = null;
					if (datas.get(i) instanceof SiteCodeEntity) {
						siteCodeEntity = (SiteCodeEntity) datas.get(i);
					} else {
						continue;
					}
					ContentValues values = new ContentValues();
					values.put(SITE_CODE_NUMBER,
							siteCodeEntity.getSiteCodeNumber());
					values.put(SITE_CODE_NAME, siteCodeEntity.getSiteCodeName());
					res = db.insert(SITE_CODE_FULL_TABLE, null, values);
					if (res > 0) {
						Log.d("插入一条网点全表", "成功");
					} else {
						Log.d("插入一条网点全表", "失败");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	/**
	 * 查询网点表的数量
	 * 
	 * @return
	 */
	public int queryAllCount() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			Cursor cursor = null;
			try {
				cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
						.rawQuery(SQL_QUERY_COUNT, null);
				if (cursor != null && cursor.moveToFirst()) {
					count = cursor.getInt(0);
				}
				closeCursor(cursor);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("queryAllCount", e.getMessage());
			} finally {
				closeCursor(cursor);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return count;
		}
	}

	/**
	 * 查询所有数据
	 * 
	 * @return
	 */
	public List<SiteCodeEntity> queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<SiteCodeEntity> data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_ALL,
					null));
			return data;
		}
	}

	private List<SiteCodeEntity> getDataFromCursor(final Cursor c) {
		List<SiteCodeEntity> lstData = new ArrayList<SiteCodeEntity>();
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					lstData.add(getSingleData(c));
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return lstData;
	}

	/**
	 * 查询网点名称
	 * 
	 * @author mgf
	 * @param siteCodeNum
	 *            网点编号
	 * @return 网点名;""：没找到
	 */
	public String querySiteCodeName(String siteCodeNum) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String siteName = "";
			Cursor c = getCursor(UnifiedStaticType.READ_DATABASE,
					SQL_NETSITE_ONLY, new String[] { siteCodeNum });
			if (c != null && c.moveToNext()) {
				siteName = c.getString(c.getColumnIndex(SITE_CODE_NAME));
				c.close();
			}
			closeDb(UnifiedStaticType.READ_DATABASE);
			return siteName;
		}
	}

	private SiteCodeEntity getSingleData(Cursor c) {
		SiteCodeEntity data = new SiteCodeEntity();
		data.setSiteCodeNumber(c.getString(c.getColumnIndex(SITE_CODE_NUMBER)));
		data.setSiteCodeName(c.getString(c.getColumnIndex(SITE_CODE_NAME)));
		return data;
	}

	@Override
	public String getMaxVersion() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			String version = "0";
			Cursor c = null;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
				c = db.rawQuery(getMaxVersionSql(SITE_CODE_FULL_TABLE), null);
				if (c != null && c.moveToNext()) {
					version = c.getString(c
							.getColumnIndex(StoBaseConstant.VERSION));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeCursor(c);
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return version;
		}
	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(SITE_CODE_FULL_TABLE, null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				db.delete(SITE_CODE_FULL_TABLE, STATUS + "=?",
						new String[] { status });
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}
	}

	@Override
	public ContentValues buildContentValues(OrgInfo entity) {
		ContentValues values = new ContentValues();
		values.put(SITE_CODE_NUMBER, entity.getKey());
		values.put(SITE_CODE_NAME, entity.getValue());
		values.put(StoSiteCodeConstant.ID, entity.id);
		values.put(StoSiteCodeConstant.VERSION, entity.getVersion());
		values.put(StoSiteCodeConstant.BACKUP1, entity.getBackup1());
		values.put(STATUS, entity.status);
		return values;
	}

	/**
	 * 插入多数据
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void insertOrReplace(List<OrgInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (OrgInfo info : datas) {
					long res = -1;
					ContentValues values = buildContentValues(info);
					// res = db.insert(SITE_CODE_FULL_TABLE, null, values);
					// if (res > 0) {
					// Log.d("插入一条网点全表", "成功");
					// } else {
					if (replace(values)) {
						Log.d("插入一条网点全表", "成功");
					} else {
						Log.d("插入一条网点全表", "失败");
						// }
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}
}
